<?php
namespace app\common\response;

use think\Response;
use think\exception\HttpResponseException;

class Base {
	protected $responseType = 'json';
	
	public function result($msg, $data = null, $code = 0, $type = null, array $header = [])
    {
        header('Content-Type: application/json; charset=utf-8');
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'time' => loader()->loadAny('request', 'Base')->server('REQUEST_TIME'),
            'data' => $data
        ];
        // 如果未设置类型则使用默认类型判断
        $type = $type ? : $this->responseType;

        if (isset($header['statuscode'])) {
            $code = $header['statuscode'];
            unset($header['statuscode']);
        } else {
            //未设置状态码,根据code值判断
            $code = $code >= 1000 || $code < 200 ? 200 : $code;
        }  
        $response = Response::create($result, $type, $code)->header($header);
        throw new HttpResponseException($response);
    }
}